package com.feeyo.groundservice.composewidget.util

import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.core.content.ContextCompat

/**
 *作者：QLH on 2023-08-01
 *描述：  compose的工具类：图片转换
 */

/**
 * 将drawableRes值转换为 compose的Painter资源，包括矢量资源xml
 * **/
@Stable
@Composable
fun @receiver:DrawableRes Int.drawableToPainter(): Painter = painterResource(this)

/**
 * 将drawableRes转换为 Drawable资源
 * **/
@Stable
@Composable
fun @receiver:DrawableRes Int.toDrawable(): Drawable? = with(LocalContext.current){
    ContextCompat.getDrawable(this, this@toDrawable)
}

/**根据文件名称获取id**/
@Stable
@Composable
fun String.painterResource(): Painter = with(LocalContext.current){
    this@painterResource.getDrawableId().drawableToPainter()
}

/**根据文件名称获取id**/
@Stable
@Composable
fun String.getDrawableId(): Int = with(LocalContext.current){
    resources.getIdentifier(this@getDrawableId, "drawable", packageName)
}


/**
 * 将图片文件转换为 compose的ImageBitmap资源
 * **/
@Stable
@Composable
fun String.fileToImageBitmap(): ImageBitmap = BitmapFactory.decodeFile(this).asImageBitmap()